package com.twetec.cms.adapter.pc.backend.tag;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Maps;
import com.twetec.cms.adapter.pc.backend.tag.annotation.TplTag;
import com.twetec.cms.adapter.pc.backend.tag.doc.TagDocObject;
import com.twetec.cms.common.constant.ArticleEnum;
import com.twetec.cms.common.util.validate.ValidateUtil;
import com.twetec.cms.model.po.website.*;
import com.twetec.cms.service.website.ArticleExtendService;
import com.twetec.cms.service.website.ArticleService;
import com.twetec.cms.service.website.ColumnService;
import com.twetec.cms.service.website.SiteService;
import org.apache.commons.lang3.StringUtils;
import org.beetl.core.tag.GeneralVarTagBinding;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service()
@Scope("prototype")
@TplTag("imageArticleList")
public class ImageArticleListTag extends GeneralVarTagBinding {

    @Autowired
    private ArticleService articleService;

    @Autowired
    private ColumnService columnService;

    @Autowired
    private SiteService siteService;

    @Autowired
    private ArticleExtendService articleExtendService;


    @Override
    public void render() {
        System.out.println("ImageArticleListTag");

        // 接收标签参数
        Map result = Maps.newHashMap();
        // 栏目id
        Long columnId = (this.getAttributeValue("columnId") instanceof String) ?
                Long.parseLong((String) this.getAttributeValue("columnId")) : (Long) this.getAttributeValue("columnId");
        // 页码
        Integer page = (this.getAttributeValue("page") instanceof String) ?
                Integer.parseInt((String) this.getAttributeValue("page")) : (Integer) this.getAttributeValue("page");
        // 页面容量
        Integer limit = (this.getAttributeValue("limit") instanceof String) ?
                Integer.parseInt((String) this.getAttributeValue("limit")) : (Integer) this.getAttributeValue("limit");
        // 文章类型
        String type = (String) this.getAttributeValue("type");

        // 栏目域名
//        String serverUrl = (String) this.getAttributeValue("serverUrl");

        // 域名
//        String dm = (String) this.getAttributeValue("dm");

//        String pageType = (String) this.getAttributeValue("pageType");

        // 查询栏目columnId下的属性是图片，类型是type的文章

        QueryWrapper<ArticlePO> articlePOQueryWrapper = new QueryWrapper<>();
        articlePOQueryWrapper.eq("COLUMN_ID", columnId);
        // 对比ArticleListTag添加了属性判断,和文章类型判断。
        articlePOQueryWrapper.eq("ATTRIBUTE", ArticleEnum.ATTRIBUTE_IMAGE.getValue());
        if (StringUtils.isNotEmpty(type)) {
            articlePOQueryWrapper.eq("TYPE", type);
        }
        articlePOQueryWrapper.eq("IS_RECOVERY", 0);
        articlePOQueryWrapper.orderByDesc("SORT");
        articlePOQueryWrapper.orderByAsc("ID");
        Page<ArticlePO> articlePOPage = articleService.page(new Page<>(page, limit), articlePOQueryWrapper);
        List<ArticlePO> records = articlePOPage.getRecords();

        if (!ValidateUtil.isNullOrEmpty(records)) {

            // 查询文章对应的站点的信息
//            SitePO sitePO = siteService.getById(records.get(0).getSiteId());

            // 拼上站点的域名
//            String articleUrl = sitePO.getDomainUrl();
            String articleUrl = "";

            // 栏目的静态文件存储路径
            String storageStaticPath = columnService.getStorageStaticPath(columnId);

            articleUrl = articleUrl + storageStaticPath;


            for (ArticlePO articlePO : records) {

                // 文章标题
                String title = articlePO.getTitle();
                // 发布时间 Date
                String releaseTime = DateUtil.formatDateTime(articlePO.getReleaseTime());
                // 对应url
                //String url = "1231.com";
                // 属性，返回中文
                // String attribute = ArticleEnum.getArticleEnumMap().get(articlePO.getAttribute());
                String attribute = articlePO.getAttribute();
                // 公告开始时间
                String gmtAnnouncementStart = DateUtil.formatDateTime(articlePO.getGmtAnnouncementStart());
                // 公告结束时间
                String gmtAnnouncementEnd = DateUtil.formatDateTime(articlePO.getGmtAnnouncementEnd());
                // 封面类型
                String coverType = articlePO.getCoverType();
                // 来源
                String origin = articlePO.getOrigin();
                // 作者
                String author = articlePO.getAuthor();
                // 封面
                List<Map<String, String>> coverListJson = new ArrayList<Map<String, String>>();


                // 当封面的json字符串不为空时才进行转换
                if (StringUtils.isNotEmpty(articlePO.getCover())) {
                    // 将json字符数组转化为对象
                    List<UrlConvert> urlConvertList = JSONArray.parseArray(articlePO.getCover(), UrlConvert.class);
                    // 遍历，添加到map中
                    for (UrlConvert urlConvert : urlConvertList) {
                        HashMap<String, String> coverMap = new HashMap<>();
                        coverMap.put("url", urlConvert.getFileUrl());
                        coverListJson.add(coverMap);
                    }
                }

                // 如果是预览，返回接口地址
//                if (null != pageType && pageType.equals("checkPage")) {
//                    result.put("url", serverUrl + "website/article/get-pc-template-render-content?articleId=" + articlePO.getId());
//                } else
                if (ArticleEnum.TYPE_GONG_GAO_ZI_XUN.getValue().equals(articlePO.getType()) ||
                        ArticleEnum.TYPE_TU_WEN_ZI_XUN.getValue().equals(articlePO.getType())) {
                    // 如果不是预览就返回正常链接
                    // 如果文章类型是图文和公告

                    // 查询所属栏目的encodedXpath
                    // 查询文章信息
                    ColumnPO columnPO = columnService.getById(articlePO.getColumnId());

                    // 域名
                    String url = columnPO.getEncodedXpath() + "/article/" + articlePO.getId() + ".html";
                    result.put("url", url.replace("\\", "/"));
                } else {
                    // 如果文章类型是下载文件和跳转链接,就从扩展表的content字段
                    QueryWrapper<ArticleExtendPO> articleExtendPOQueryWrapper = new QueryWrapper<>();
                    articleExtendPOQueryWrapper.eq("ARTICLE_ID", articlePO.getId());
                    ArticleExtendPO articleExtendPO = articleExtendService.getOne(articleExtendPOQueryWrapper);
                    result.put("url", articleExtendPO.getContent());
                }

                // 文章类型
                String articleType = articlePO.getType();
                // 发布途径
                String releaseChannel = articlePO.getReleaseChannel();

                // 返回标签参数
                result.put("title", title);
                result.put("releaseTime", releaseTime);
                result.put("gmtAnnouncementStart", gmtAnnouncementStart);
                result.put("gmtAnnouncementEnd", gmtAnnouncementEnd);
                result.put("coverType", coverType);
                result.put("origin", origin);
                result.put("author", author);
                result.put("coverListJson", coverListJson);
                // 只有封面的json字符串不为空时，才取出第一个
                if (!ValidateUtil.isNullOrEmpty(coverListJson)) {
                    result.put("cover", coverListJson.get(0).get("url"));
                }
//                System.out.println("++++++++++++++++++++++++++++++");
//                System.out.println(coverListJson.get(0).get("url"));
                result.put("type", articleType);
                result.put("releaseChannel", releaseChannel);

                this.binds(result);
                this.doBodyRender();
            }

        }


    }

    /**
     * 标签文档
     *
     * @return
     */
    public static TagDocObject doc() {
        TagDocObject tagDocObject = new TagDocObject();
        tagDocObject.setTagName("imageArticleList");
        tagDocObject.setDesc("图片文章列表标签");
        tagDocObject.setExample("<#imageArticleList serverUrl=\"${serverUrl}\" columnId=\"1456206462863671298\" page=\"1\" limit=\"5\" dm=\"${site.dm!}\" pageType=\"${pageType}\"  type=\"GONG_GAO_ZI_XUN\" var=\"data\">" +
                "                     <li>\n" +
                        "              <a href=\"${data.url!}\">\n" +
                        "                <img src=\"${data.cover!}\" alt=\"\">\n" +
                        "                <p>${data.title!}</p>\n" +
                        "              </a>\n" +
                        "            </li>\n" +
                "                </#imageArticleList>");

        tagDocObject.setParamDesc("columnId：所属栏目id\n" +
                "serverUrl：资讯发布系统的域名或IP和Port\n" +
                "dm：站点域名\n" +
                "pageType：用于标识是生成静态页面还是预览（预览：checkPage，生成：null或staticPage）\n" +
                "page：页码\n" +
                "limit：页条目数\n" +
                "type：文章类型(图文咨询TU_WEN_ZI_XUN,下载文件XIA_ZAI_WEN_JIAN,跳转链接TIAO_ZHUAN_LIAN_JIE,公告咨询GONG_GAO_ZI_XUN)\n" +
                "--------- var: 标签的数据结果集 ---------\n" +
                "title：文章标题\n" +
                "releaseTime：发布时间\n" +
                "url：对应url\n" +
                "releaseChannel：发布渠道(PC,H5,API)\n" +
                "cover：封面图\n" +
                "origin：来源\n" +
                "author：作者\n" +
                "type：文章类型(图文咨询TU_WEN_ZI_XUN,下载文件XIA_ZAI_WEN_JIAN,跳转链接TIAO_ZHUAN_LIAN_JIE,公告咨询GONG_GAO_ZI_XUN)");

        tagDocObject.setOtherDesc("无");

        return tagDocObject;
    }

}
